library(ggplot2)
library(readr)
chic <- read_csv("ggplot2/ggModify/chicago-nmmaps.csv")

# 添加LOESS或GAM平滑
# 可以简单地使用stat_smooth()—甚至不需要公式。
# 如果少于1000个点，就添加LOESS平滑，否则就添加一个GAM(广义加性模型，method=“GAM”)平滑。
ggplot(chic, aes(x = date, y = temp)) +
  labs(x = "Year", y = "Temperature (°F)") +
  stat_smooth() +
  geom_point(color = "gray40", alpha = .5)

# 添加线性拟合
# 虽然默认值是LOESS或GAM平滑，但也很容易添加一个标准线性拟合:
ggplot(chic, aes(x = temp, y = death)) +
   labs(x = "Temperature (°F)", y = "Deaths") +
   stat_smooth(method = "lm", se = FALSE,
               color = "firebrick", size = 1.3) +
   geom_point(color = "gray40", alpha = .5)

# 指定平滑公式
# ggplot2允许你指定想要使用的模型。也许你想用多项式回归?
ggplot(chic, aes(x = o3, y = temp))+
  labs(x = "Ozone Level", y = "Temperature (°F)") +
  geom_smooth(
    method = "lm",
    formula = y ~ x + I(x^2) + I(x^3) + I(x^4) + I(x^5),
    color = "black",
    fill = "firebrick"
  ) +
  geom_point(color = "gray40", alpha = .3)

# 或者假设你想要增加GAM的维度(添加一些额外的平滑摆动):
cols <- c("darkorange2", "firebrick", "dodgerblue3")

ggplot(chic, aes(x = date, y = temp)) +
  geom_point(color = "gray40", alpha = .3) +
  labs(x = "Year", y = "Temperature (°F)") +
  stat_smooth(aes(col = "1000"),
              method = "gam",
              formula = y ~ s(x, k = 1000),
              se = FALSE, size = 1.3) +
  stat_smooth(aes(col = "100"),
              method = "gam",
              formula = y ~ s(x, k = 100),
              se = FALSE, size = 1) +
  stat_smooth(aes(col = "10"),
              method = "gam",
              formula = y ~ s(x, k = 10),
              se = FALSE, size = .8) +
  scale_color_manual(name = "k", values = cols)
  